<template>
  <div class="match-game">
    <header class="game-header glass">
      <el-button @click="$router.back()" text><el-icon><ArrowLeft /></el-icon>返回</el-button>
      <div class="score-board">
        <span>得分: {{ score }}</span>
        <span>正确: {{ correctCount }}/{{ totalPairs }}</span>
        <span>时间: {{ time }}s</span>
      </div>
    </header>

    <div class="game-content">
      <div class="cards-grid" v-if="!gameOver">
        <div 
          v-for="card in cards" 
          :key="card.id"
          class="card glass"
          :class="{ 
            flipped: card.flipped, 
            matched: card.matched,
            selected: selected.includes(card.id)
          }"
          @click="selectCard(card)"
        >
          <div class="card-inner">
            <div class="card-front">?</div>
            <div class="card-back">{{ card.content }}</div>
          </div>
        </div>
      </div>

      <div class="game-over glass" v-else>
        <h2>🎉 游戏结束！</h2>
        <p>得分: {{ score }}</p>
        <p>正确配对: {{ correctCount }}/{{ totalPairs }}</p>
        <p>用时: {{ time }}秒</p>
        <el-button type="primary" size="large" @click="restart">再玩一次</el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { gameApi } from '@/api/game'

const emit = defineEmits(['finish'])

interface Card {
  id: number
  pairId: number
  content: string
  type: 'word' | 'chinese'
  flipped: boolean
  matched: boolean
}

const cards = ref<Card[]>([])
const selected = ref<number[]>([])
const score = ref(0)
const correctCount = ref(0)
const time = ref(0)
const gameOver = ref(false)
const totalPairs = ref(6)
let timer: any = null

const loadWords = async () => {
  try {
    // 从路由获取难度参数
    const route = useRoute()
    const difficulty = route.query.difficulty || 'hard'
    
    const res = await gameApi.getRandomWords({ count: 6, difficulty: difficulty as string })
    if (res.success && res.data) {
      const wordPairs = res.data
      const gameCards: Card[] = []
      
      wordPairs.forEach((word: any, index: number) => {
        gameCards.push({
          id: index * 2,
          pairId: index,
          content: word.word,
          type: 'word',
          flipped: false,
          matched: false
        })
        gameCards.push({
          id: index * 2 + 1,
          pairId: index,
          content: word.chinese,
          type: 'chinese',
          flipped: false,
          matched: false
        })
      })
      
      // 打乱卡片
      cards.value = gameCards.sort(() => Math.random() - 0.5)
    }
  } catch (error) {
    ElMessage.error('加载单词失败')
  }
}

const selectCard = (card: Card) => {
  if (card.matched || card.flipped || selected.value.length >= 2) return
  
  card.flipped = true
  selected.value.push(card.id)
  
  if (selected.value.length === 2) {
    checkMatch()
  }
}

const checkMatch = () => {
  const [id1, id2] = selected.value
  const card1 = cards.value.find(c => c.id === id1)!
  const card2 = cards.value.find(c => c.id === id2)!
  
  if (card1.pairId === card2.pairId) {
    // 匹配成功
    card1.matched = true
    card2.matched = true
    correctCount.value++
    score.value += 10
    ElMessage.success('配对成功！+10分')
    selected.value = []
    
    // 检查是否全部完成
    if (correctCount.value === totalPairs.value) {
      finishGame()
    }
  } else {
    // 匹配失败
    setTimeout(() => {
      card1.flipped = false
      card2.flipped = false
      selected.value = []
    }, 1000)
  }
}

const finishGame = () => {
  gameOver.value = true
  if (timer) clearInterval(timer)
  emit('finish', score.value, correctCount.value)
}

const restart = () => {
  score.value = 0
  correctCount.value = 0
  time.value = 0
  gameOver.value = false
  selected.value = []
  loadWords()
  startTimer()
}

const startTimer = () => {
  timer = setInterval(() => {
    time.value++
  }, 1000)
}

onMounted(() => {
  loadWords()
  startTimer()
})

onUnmounted(() => {
  if (timer) clearInterval(timer)
})
</script>

<style scoped lang="scss">
.match-game {
  width: 100%;
  min-height: 100vh;
  padding: 20px;
  overflow-y: auto;
  overflow-x: hidden;
}

.game-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 30px;
  margin-bottom: 30px;
  
  .score-board {
    display: flex;
    gap: 30px;
    color: white;
    font-size: 1.2rem;
    font-weight: bold;
  }
}

.game-content {
  max-width: 800px;
  margin: 0 auto;
}

.cards-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
  
  @media (max-width: 768px) {
    grid-template-columns: repeat(3, 1fr);
  }
}

.card {
  aspect-ratio: 1;
  cursor: pointer;
  perspective: 1000px;
  
  &.matched {
    .card-inner {
      opacity: 0.5;
      pointer-events: none;
    }
  }
  
  &.selected {
    box-shadow: 0 0 20px rgba(103, 194, 58, 0.8);
  }
  
  .card-inner {
    width: 100%;
    height: 100%;
    position: relative;
    transition: transform 0.6s;
    transform-style: preserve-3d;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  &.flipped .card-inner {
    transform: rotateY(180deg);
  }
  
  .card-front,
  .card-back {
    position: absolute;
    width: 100%;
    height: 100%;
    backface-visibility: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
    font-weight: bold;
    color: white;
    border-radius: 10px;
  }
  
  .card-front {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    font-size: 3rem;
  }
  
  .card-back {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    transform: rotateY(180deg);
    padding: 10px;
    text-align: center;
    word-break: break-all;
  }
}

.game-over {
  padding: 60px 40px;
  text-align: center;
  
  h2 {
    color: white;
    font-size: 2.5rem;
    margin-bottom: 30px;
  }
  
  p {
    color: rgba(255, 255, 255, 0.9);
    font-size: 1.3rem;
    margin: 15px 0;
  }
  
  .el-button {
    margin-top: 30px;
  }
}
</style>

